import React from "react";
import {
  Row,
  Col,
  Button,
  message,
  PageHeader,
  Spin,
  Input,
  Space,
} from "antd";
import BraftEditor from "braft-editor";
import "braft-editor/dist/index.css";
import { connect } from "react-redux";

import { _addCourse } from "../../../../utils/course/index";
const url = require("../../../../utils/conUrl");

class Index extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      user_id: null,
      isshow: false,
      isLoading: false,
      course_title: null,
      course_content: BraftEditor.createEditorState(null),
    };
  }

  submitContent = async () => {
    if (!this.state.course_title || !this.state.course_content) {
      message.info("请填写标题和内容");
      return false;
    }
    this.setState({ isLoading: true });
    const htmlString = this.state.course_content.toHTML();
    let tempData = {
      tch_id: this.props.state.data.tch_id,
      course_title: this.state.course_title,
      course_content: htmlString,                 
    };
    _addCourse(tempData)
      .then((res) => {
        if (res.status === 200 && res.data.code === 0) {
          this.setState({ isLoading: false });
          message.success("新增成功", 1.5).then(() => {
            window.history.back();
          });
        }
      })
      .catch(() => {
        this.setState({ isLoading: false });
        message.error("服务器错误");
      });
  };
  onInputChange = (e) => {
    let inputValue = e.target.value;
    let inputName = e.target.name;
    this.setState({
      [inputName]: inputValue,
    });
  };
  handleEditorChange = (course_content) => {
    this.setState({ course_content });
  };
  // 预览
  preview = () => {
    if (window.previewWindow) {
      window.previewWindow.close();
    }

    window.previewWindow = window.open();
    window.previewWindow.document.write(this.buildPreviewHtml());
    window.previewWindow.document.close();
  };
  buildPreviewHtml() {
    return `
      <!Doctype html>
      <html>
        <head>
          <title>Preview Content</title>
          <style>
            html,body{
              height: 100%;
              margin: 0;
              padding: 0;
              overflow: auto;
              background-color: #f1f2f3;
            }
            .container{
              box-sizing: border-box;
              width: 1000px;
              max-width: 100%;
              min-height: 100%;
              margin: 0 auto;
              padding: 30px 20px;
              overflow: hidden;
              background-color: #fff;
              border-right: solid 1px #eee;
              border-left: solid 1px #eee;
            }
            .container img,
            .container audio,
            .container video{
              max-width: 100%;
              height: auto;
            }
            .container p{
              white-space: pre-wrap;
              min-height: 1em;
            }
            .container pre{
              padding: 15px;
              background-color: #f1f1f1;
              border-radius: 5px;
            }
            .container blockquote{
              margin: 0;
              padding: 15px;
              background-color: #f1f1f1;
              border-left: 3px solid #d1d1d1;
            }
          </style>
        </head>
        <body>
          <div class="container">${this.state.course_content.toHTML()}</div>
        </body>
      </html>
    `;
  }

  render() {
    const myUploadFn = (param) => {
      const serverURL = "/api/up_qt";
      const xhr = new XMLHttpRequest();
      const fd = new FormData();

      const successFn = (res) => {
        // 假设服务端直接返回文件上传后的地址
        // 上传成功后调用param.success并传入上传后的文件地址
        param.success({
          url: `/file/qt/` + JSON.parse(xhr.response).data.data.filename,
          meta: {
            id: "xxx",
            title: "教学视频",
            alt: "教学",
            loop: false, // 指定音视频是否循环播放
            autoPlay: false, // 指定音视频是否自动播放
            controls: true, // 指定音视频是否显示控制栏
            poster: url.api + "/file/avatar/fm.png", // 指定视频播放器的封面
          },
        });
      };

      const progressFn = (event) => {
        // 上传进度发生变化时调用param.progress
        param.progress((event.loaded / event.total) * 100);
      };

      const errorFn = (response) => {
        // 上传发生错误时调用param.error
        param.error({
          msg: "unable to upload.",
        });
      };

      xhr.upload.addEventListener("progress", progressFn, false);
      xhr.addEventListener("load", successFn, false);
      xhr.addEventListener("error", errorFn, false);
      xhr.addEventListener("abort", errorFn, false);

      fd.append("file", param.file);
      xhr.open("POST", serverURL, true);
      xhr.send(fd);
    };
    const { course_content } = this.state;
    const excludeControls = [
      //   "media",
      "emoji",
    ];
    const extendControls = [
      {
        key: "custom-button",
        type: "component",
        component: (
          <button
            type="button"
            className="control-item button upload-button"
            data-title="预览"
            onClick={this.preview}
          >
            预览
          </button>
        ),
      },
    ];
    return (
      <div style={{ minHeight: 360 }}>
        <Row>
          {/* <Col span={4}>
        <Button type="primary" block>
          保存修改
        </Button>
      </Col> */}
          <Col span={24}>
            <PageHeader
              ghost={false}
              onBack={() => window.history.back()}
              subTitle="新增教程"
              extra={[
                <Button type="primary" block onClick={this.submitContent}>
                  确认保存
                </Button>,
              ]}
            ></PageHeader>
          </Col>
        </Row>
        <br />
        <Row>
          <Col span={24}>
            <Spin tip="Loading..." spinning={this.state.isLoading}>
              <Space direction="vertical">
                <Input
                  placeholder="标题"
                  addonBefore="标题"
                  allowClear
                  onChange={this.onInputChange}
                  name="course_title"
                />
                <BraftEditor
                  value={course_content}
                  onChange={this.handleEditorChange}
                  onSave={this.submitContent}
                  extendControls={extendControls}
                  excludeControls={excludeControls}
                  placeholder="^-^在这里书写内容"
                  media={{ uploadFn: myUploadFn }}
                />
              </Space>
            </Spin>
          </Col>
        </Row>
      </div>
    );
  }
}

const mapStateToProps = (state) => {
  return {
    state: state.user,
  };
};
const actionCreator = {};
export default connect(mapStateToProps, actionCreator)(Index);
